//
//  UserAccountModel.swift
//  swiftImitationWeibo
//
//  Created by 杨果果 on 16/7/10.
//  Copyright © 2016年 yang. All rights reserved.
//

import UIKit

class UserAccountModel: NSObject, NSCoding {
    var access_token: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    //过期时间
    var expiresDate: NSDate?
    //uid  授权用户的ID
    var uid: Int64 = 0
    
    //用户头像
    var name: String?
    
    //用户名
    var avatar_large: String?
    //构造函数
    init(dic: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dic)
        
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    //重写description属性  打印时候不出现地址 而是属性值
    override var description: String {
        let key = ["access_token", "expiresDate", "uid", "name", "avatar_large"]
        return dictionaryWithValuesForKeys(key).description
    }
    //归档

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档
    required init?(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
        
    }
    //保存用户对象
    func saveUserAccount() -> Bool {
        //获取路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("user.archive")
//        print(path)
        //存储
        let result = NSKeyedArchiver.archiveRootObject(self, toFile: path)

        return result
        
    }
    //通过路径读取用户对象
    //  为什么加class   、类方法、、、、、、//////////////////////////////////////
    class func loadUserAccount() -> UserAccountModel? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("user.archive")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccountModel
    }
    
    
    
}
